/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uit_vendor_management;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRTableModelDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

/**
 *
 * @author Minh Nguyen
 */
public class SalesReportForm extends javax.swing.JFrame {

    /**
     * Properties
     */
    String SoPhieuXuat = Language._("SALESREPORT_FORM_SO_PHIEU_XUAT_COLUMN_TITLE");
    String TongTriGia = Language._("SALESREPORT_FORM_TONG_TRI_GIA_COLUMN_TITLE");
    String TyLe = Language._("SALESREPORT_FORM_TY_LE_COLUMN_TITLE");
    String MaDaiLy = Language._("SALESREPORT_FORM_MA_DAI_LY_COLUMN_TITLE");
    String BeginQuery = 
            "SELECT DOANHSO.ID, DOANHSO.SoPhieuXuat as '" + SoPhieuXuat + "', "
            + "DOANHSO.TongTriGia as '" + TongTriGia + "', "
            + "DOANHSO.TyLe as '" + TyLe + "', "
            + "DOANHSO.MaDaiLy as '" + MaDaiLy + "' "
            + "FROM DOANHSO WHERE DOANHSO.Thang = ";
    String BeginQueryReport = 
            "SELECT DOANHSO.ID, DOANHSO.SoPhieuXuat as '" + SoPhieuXuat + "', "
            + "DOANHSO.TongTriGia as '" + TongTriGia + "', "
            + "DOANHSO.TyLe as '" + TyLe + "', "
            + "DOANHSO.MaDaiLy as '" + MaDaiLy + "', DOANHSO.Thang as 'Tháng' "
            + "FROM DOANHSO WHERE DOANHSO.Thang = ";
    /**
     * Creates new form SalesReportForm
     */
    public SalesReportForm() {
        initComponents();       
        /**
         * DefaultTable: 
         *  - Create TitleRows for table
         *  - Don't have DataRows (will be created when click btnLapBaoCao)
         */
        this.InitLanguage();
        String[] TitleRows = new String[] { "ID", SoPhieuXuat, TongTriGia, TyLe, MaDaiLy };
        TableModel dtm = new DefaultTableModel(new String[][] {}, TitleRows);
        tbeKetQua.setModel(dtm);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblBaoCaoDoanhSo = new javax.swing.JLabel();
        lblThang = new javax.swing.JLabel();
        tfdThang = new javax.swing.JTextField();
        btnXuatFilePdf = new javax.swing.JButton();
        btnLapBaoCao = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbeKetQua = new javax.swing.JTable();

        setResizable(false);

        lblBaoCaoDoanhSo.setFont(new java.awt.Font("Calibri", 0, 48)); // NOI18N
        lblBaoCaoDoanhSo.setText("BÁO CÁO DOANH SỐ");

        lblThang.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        lblThang.setText("Tháng");

        tfdThang.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tfdThang.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfdThangFocusLost(evt);
            }
        });

        btnXuatFilePdf.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        btnXuatFilePdf.setText("Xuất File Pdf");
        btnXuatFilePdf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXuatFilePdfActionPerformed(evt);
            }
        });

        btnLapBaoCao.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        btnLapBaoCao.setText("Lập Báo Cáo");
        btnLapBaoCao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLapBaoCaoActionPerformed(evt);
            }
        });

        tbeKetQua.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tbeKetQua.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tbeKetQua);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(38, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblBaoCaoDoanhSo)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblThang)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(tfdThang, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLapBaoCao)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnXuatFilePdf))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGap(28, 28, 28))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblBaoCaoDoanhSo, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblThang)
                    .addComponent(tfdThang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnXuatFilePdf)
                    .addComponent(btnLapBaoCao))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public final void InitLanguage() 
    {
        this.lblBaoCaoDoanhSo.setText(Language._("SALESREPORT_FORM_TITLE_LBL"));
        this.lblThang.setText(Language._("SALESREPORT_FORM_THANG_LBL"));
        this.btnLapBaoCao.setText(Language._("SALESREPORT_FORM_LAP_BAO_CAO_BTN"));
        this.btnXuatFilePdf.setText(Language._("SALESREPORT_FORM_XUAT_FILE_PDF_BTN"));
    }
        
    private void tfdThangFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfdThangFocusLost
        // TODO add your handling code here:
        String regex = "^[1-9]|1[0-2]*$";
        if(!"".equals(tfdThang.getText()))
             if(tfdThang.getText().matches(regex))
             {
                 tfdThang.setBackground(Color.white);
             }
             else
             {
                 tfdThang.setBackground(Color.red);
             }
        else
            tfdThang.setBackground(Color.white);
    }//GEN-LAST:event_tfdThangFocusLost

    private void btnXuatFilePdfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXuatFilePdfActionPerformed
        // TODO add your handling code here:
                try{
            if(tfdThang.getBackground() != Color.red)
            {
                if(!"".equals(tfdThang.getText()))
                {
                    InputStream input = new FileInputStream(new File("jrxml/JasperReport.jrxml"));
                    JasperDesign jasperDesign = JRXmlLoader.load(input);
                    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
                    String Query = BeginQueryReport;
                    Query += tfdThang.getText();
                    QueryResult result = Database.instance.Query(Query);
                    JRDataSource datasource = new JRTableModelDataSource(result.Table);
                    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, datasource);
                    //JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);
                    JFileChooser chooser = new JFileChooser();
                    int returnVal = chooser.showSaveDialog(SalesReportForm.this);
                   // FileFilter filter = new FileFilter();
                    if(returnVal == JFileChooser.APPROVE_OPTION) {
                            String t = chooser.getSelectedFile().toString() + ".pdf";
                            OutputStream output = new FileOutputStream(new File(t));
                            JasperExportManager.exportReportToPdfStream(jasperPrint, output);
                            output.close();
                    }
                }
            }
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnXuatFilePdfActionPerformed

    private void btnLapBaoCaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLapBaoCaoActionPerformed
        // TODO add your handling code here:
        if(tfdThang.getBackground() != Color.red)
        {
            String Query = BeginQuery;
            if(!"".equals(tfdThang.getText()))
            {
                Query += tfdThang.getText();
                QueryResult result = Database.instance.Query(Query);
                tbeKetQua.setModel(result.Table);
            }
        }
    }//GEN-LAST:event_btnLapBaoCaoActionPerformed

        
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SalesReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SalesReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SalesReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SalesReportForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SalesReportForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLapBaoCao;
    private javax.swing.JButton btnXuatFilePdf;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblBaoCaoDoanhSo;
    private javax.swing.JLabel lblThang;
    private javax.swing.JTable tbeKetQua;
    private javax.swing.JTextField tfdThang;
    // End of variables declaration//GEN-END:variables
}
